'''
* This is the projet for brtc R&D  Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description 将自定义工具参数列表转换为OpenAI兼容的JSON Schema
* @File: convert_openai_tool.py
* @Time: 2025/01/27 14:30:00
* @All Rights Reserve By Brtc
'''

from copy import deepcopy
from typing import Any, Dict, List


SCHEMA_TYPE_MAP: Dict[str, str] = {
    "string": "string",
    "number": "number",
    "integer": "integer",
    "boolean": "boolean",
    "object": "object",
    "array": "array",
}


def convert_openai_tool(tool_defs: Any) -> List[Dict[str, Any]]:
    """
    * @Author Leon-liao
    * @Function: convert_openai_tool
    * @Description //通用入口，接收不同格式的工具定义并输出OpenAI兼容格式
    * @Date :2025/01/27 14:30:00
    * @Param: tool_defs:可以是函数定义列表或包含type/function的列表
    * @return: 返回OpenAI工具Schema列表
    """
    if isinstance(tool_defs, dict):
        raw_tools: List[Dict[str, Any]] = [tool_defs]
    else:
        raw_tools = list(tool_defs)

    formatted: List[Dict[str, Any]] = []
    for tool in raw_tools:
        if "type" in tool and "function" in tool:
            formatted.append(tool)
        else:
            formatted.append({"type": "function", "function": tool})

    converted_tools: List[Dict[str, Any]] = []

    for tool in formatted:
        tool_copy = deepcopy(tool)
        function_block = tool_copy.get("function", {})
        params = function_block.get("parameters")

        # 如果已经是JSON Schema结构，则直接保留
        if isinstance(params, dict) and "properties" in params:
            converted_tools.append(tool_copy)
            continue

        parameter_list = params or []
        properties: Dict[str, Any] = {}
        required_fields: List[str] = []

        for param in parameter_list:
            name = param.get("name")
            if not name:
                continue

            raw_type = str(param.get("type", "string")).lower()
            schema_type = SCHEMA_TYPE_MAP.get(raw_type, "string")
            prop: Dict[str, Any] = {
                "type": schema_type,
                "description": param.get("description", ""),
            }

            if "enum" in param:
                prop["enum"] = param["enum"]
            if "default" in param:
                prop["default"] = param["default"]

            properties[name] = prop
            if param.get("required", True):
                required_fields.append(name)

        schema: Dict[str, Any] = {"type": "object", "properties": properties}
        if required_fields:
            schema["required"] = required_fields

        function_block["parameters"] = schema
        tool_copy["function"] = function_block
        converted_tools.append(tool_copy)

    return converted_tools